package com.example.xmlfactory.parse.dom;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Parser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by huangbei on 2017/9/12.
 */

public class DomParser implements Parser{


    @Override
    public List parse(InputStream inputStream, Class cl) throws Exception {
        List list = new ArrayList();
        try{
            ClassMsg classMsg = new ClassMsg(cl);

            //解析
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputStream);
            Element rootElement = doc.getDocumentElement();
            NodeList items = rootElement.getElementsByTagName(classMsg.getClassName());
            for(int i=0;i<items.getLength();i++){
                Node item = items.item(i);
                NodeList properties = item.getChildNodes();
                for(int j=0;j<properties.getLength();j++){
                    Node property = properties.item(j);
                    String nodename = property.getNodeName();
                    if(classMsg.isProperty(nodename)) {
                        String value = property.getFirstChild().getNodeValue();
                        classMsg.addValue(nodename, value);
                    }
                }
                Object obj = classMsg.generateObj();
                if(obj!=null) {
                    list.add(obj);
                }
            }

            return list;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
